package leetcode.code0722;

import java.util.ArrayList;
import java.util.List;
import java.util.StringJoiner;

import leetcode.helper.H;

/*/ declare members;/**/

//["main() {", "/* here is commments", "  // still comments */", "   double s = 33;", "   cout << s;", "}"]
// ["struct Node{", "    /*/ declare members;/**/", "    int size;", "    /**/int val;", "};"]
//["void func(int k) {", "// this function does nothing /*", "   k = k*2/4;", "   k = k/2;*/", "}"]

public class Solution {

	public List<String> removeComments(String[] source) {
		String str = String.join("\n", source);
		StringBuffer sb = new StringBuffer();
		while (str.length() > 0) {
			int s = str.indexOf("/*"), d = str.indexOf("//");
			if (s == -1 && d == -1) {
				sb.append(str);
				break;
			}
			if (s != -1 && (d == -1 || s < d)) {// /*区间
				sb.append(str.substring(0, s));
				str = str.substring(s + 2);
				int e = str.indexOf("*/");
				str = str.substring(e + 2);
			} else if (d != -1 && (s == -1 || d < s)) {
				sb.append(str.substring(0, d));
				str = str.substring(d + 2);
				int e = str.indexOf("\n");
				if (e == -1) {
					break;
				}
				str = str.substring(e);
			}
		}
		String[] strs = sb.toString().split("\n");
		List<String> ans = new ArrayList<>();
		for (String s : strs) {
			if (s.length() > 0) {
				ans.add(s);
			}
		}
		return ans;
	}

	public static void main(String[] args) {
		Solution so = new Solution();
//		so.removeComments(H.str2array2("[\"a/*/b//*c\",\"blank\",\"d//*e*//f\"]"));
//		so.removeComments(H.str2array2("[\"a/*/b//*c\",\"blank\",\"d//*e/*/f\"]"));
//		so.removeComments(H.str2array2("[\"a//*b//*c\",\"blank\",\"d/*/e*//f\"]"));
//		so.removeComments(H.str2array2("[\"main() {\", \"  Node* p;\", \"  /* declare a Node\", \"  /*float f = 2.0\", \"   p->val = f;\", \"   /**/\", \"   p->val = 1;\", \"   //*/ cout << success;*/\", \"}\", \" \"]"));
//		so.removeComments(H.str2array2("[\"struct Node{\", \"    /*/ declare members;/**/\", \"    int size;\", \"    /**/int val;\", \"};\"]"));
		so.removeComments(H.str2array2(
				"[\"/*Test program */\", \"int main()\", \"{ \", \"  // variable declaration \", \"int a, b, c;\", \"/* This is a test\", \"   multiline  \", \"   comment for \", \"   testing */\", \"a = b + c;\", \"}\"]"));

//		String string = "abc/**123**/abcc/**123**/abc123\n444";
//		System.out.println(string.indexOf("\n"));
//		System.out.println(string.substring(0, 0));
//		System.out.println(string.indexOf("/*"));
//		System.out.println(string.indexOf("*/"));
//		System.out.println(string.substring(0, string.indexOf("/*")));
//		System.out.println(string.substring(string.indexOf("*/") + 2));
//		System.out.println(string.indexOf('b'));
//		System.out.println(string.substring(0, string.indexOf('b')));
	}
}
